#include    <stdlib.h>
#include    <stdio.h>
#include    <unistd.h>
#include    <string.h>
#include    "json.h"

void  GetValByKey(json_object *jobj, const  char  *sname)
{
    int i;
    json_object     *pval = NULL, *jo_arr = NULL;
    enum json_type type;
    // pval = json_object_object_get(jobj, sname);
    // 新版本的 json-c 推荐使用 json_object_object_get_ex
    json_object_object_get_ex(jobj, sname, &pval);
    if(NULL != pval){
        type = json_object_get_type(pval);
        switch(type)
        {
            case    json_type_null:
                printf("Key:%s  value: %s\n", sname, "is null");
                break;
            case    json_type_boolean:
                printf("Key:%s  value: %s\n", sname, json_object_get_string(pval));
                break;
            case    json_type_double:
                printf("Key:%s  value: %f\n", sname, json_object_get_double(pval));
                break;
            case    json_type_int:
                printf("Key:%s  value: %d\n", sname, json_object_get_int(pval));
                break;
            case    json_type_object:
                printf("Key:%s  value: %s\n", sname, json_object_get_string(pval));
                break;
            case    json_type_array:
                //printf("Key:%s  value: %s\n", sname, json_object_get_string(pval));
                printf("array length: %d\n", json_object_array_length(pval));
                for (i=0; i < json_object_array_length(pval); i++)
                {
                    jo_arr = json_object_array_get_idx(pval, i);
                    GetValByKey(jo_arr, "name");
                }
                break;
            case    json_type_string:
                printf("Key:%s  value: %s\n", sname, json_object_get_string(pval));
                break;
            default:
                break;
        }
    }

    json_object_put(pval);
}

int  main(int argc, char *argv[])
{
    json_object    *pobj = NULL;

    //pobj = json_tokener_parse("{ \"abc\": 12, \"foo\": \"bar\", \"bool0\": false, \"bool1\": true, \"arr\": [ 1, 2, 3, null, 5 ] }");

    //printf("new_obj.to_string()=%s\n", json_object_to_json_string(pobj));

    //json_parse(pobj);
    
    if (argc != 3)
    {
        fprintf(stdout, "Usage: ./psjson <json file> <keywords>\n");
        return 1;
    }

    pobj = json_object_from_file(argv[1]);
    GetValByKey(pobj, argv[2]);
/*
    json_object_object_del(pobj, "foo");
    json_object_object_add(pobj, "foo", json_object_new_string("fark"));
    json_object_object_add(pobj, "Age", json_object_new_int(200));
    GetValByKey(pobj,  "Age");
    json_object_to_file("/home/konghy/aboutme/cparsejson/new.json", pobj);
*/
    json_object_put(pobj);
    return 0;
}
